package org.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;

import java.nio.ByteBuffer;

/**
 * @author wind
 * @create 2025-01-15 11:04
 */
public class HelloWorldClient {
    public static void main(String[] args) {
        new HelloWorldClient().init();
    }

    public void init(){
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel c) throws Exception {
                //c.pipeline().addLast(new StringDecoder());
                //c.pipeline().addLast(new StringEncoder());
                c.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                c.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = msg instanceof ByteBuf ? (ByteBuf)msg : null;
                        byte[] b = new byte[16];
                        buf.readBytes(b,0,buf.readableBytes());
                        System.out.println(new String(b));
                    }
                });
            }
        });
        try {
            Channel channel = bootstrap.connect("localhost",8080).sync().channel();
            channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("zhangsan".getBytes()));
            Thread.sleep(2000);
            channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("lisi".getBytes()));
            Thread.sleep(2000);
            channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("wangwu".getBytes()));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
